package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.acticle.domain.Destination;
import cn.wolfcode.luowowo.acticle.domain.Travel;
import cn.wolfcode.luowowo.acticle.domain.TravelContent;
import cn.wolfcode.luowowo.acticle.query.StrategyDetailQueryObject;
import cn.wolfcode.luowowo.acticle.query.TravelQueryObject;
import cn.wolfcode.luowowo.acticle.service.IDestinationService;
import cn.wolfcode.luowowo.acticle.service.IStrategyDetailService;
import cn.wolfcode.luowowo.acticle.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQueryObject;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 游记资源管理器
 */
@Controller
@RequestMapping("/travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;


    //游记列表
    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo") TravelQueryObject qo) {
        //pageInfo   //t.author.nickname
        qo.setState(Travel.STATE_RELEASE);
        model.addAttribute("pageInfo", travelService.query(qo));
        //tcs 最新的三条游记评论
        model.addAttribute("tcs", travelCommentService.getCommentTop10());
        //hotDetails 查询阅读量最高的前五条攻略明细
        StrategyDetailQueryObject detailQO = new StrategyDetailQueryObject();
        detailQO.setPageSize(5);
        detailQO.setOrder("sd.viewnum desc");
        model.addAttribute("hotDetails", strategyDetailService.query(detailQO).getList());
        return "travel/list";
    }

    //游记明细
    @RequestMapping("/detail")
    public String detail(Model model, Long id) {  //游记id
        //detail  //detail.travelContent.content   //detail.dest
        Travel travel = travelService.get(id);
        TravelContent travelContent = travelService.getTravelContent(id);
        travel.setTravelContent(travelContent);
        model.addAttribute("detail", travel);

        //toasts 目的地吐司
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        if (toasts.size() > 0) {
            toasts.remove(toasts.size() - 1);
        }
        model.addAttribute("toasts", toasts);

        //sds 该目的地下阅读量为前3的攻略明细
        model.addAttribute("sds", strategyDetailService.getDetailTop3ByDestId(travel.getDest().getId()));

        //ts  该目的地下阅读量为前3的游记
        model.addAttribute("ts", travelService.getTravelTop3ByDestId(travel.getDest().getId()));

        //list 评论数据
        TravelCommentQueryObject qo = new TravelCommentQueryObject();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);
        model.addAttribute("list", travelCommentService.query(qo).getContent());

        //阅读数加1
        travelStatisRedisService.numIncrease(id, 0);

        //共享vo
        model.addAttribute("vo", travelStatisRedisService.getTravelStatisVo(id));
        return "travel/detail";
    }

    //新增编辑游记
    @RequireLogin //须登录才能访问
    @RequestMapping("/input")
    public String input(Model model, Long id) {  //id为游记id
        //destinations
        model.addAttribute("destinations", destinationService.getDestinationByDeep(3));
        //tv 攻略内容   //tv.travelContent.content
        if (id != null) {
            Travel travel = travelService.get(id);
            TravelContent travelContent = travelService.getTravelContent(id);
            travel.setTravelContent(travelContent);
            model.addAttribute("tv", travel);
        }
        return "travel/input";
    }

    @Value("${file.path}")
    private String filePath;

    //上传封面
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic) {
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }

    //百度复文本编辑器图片上传
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    //保存操作
    @RequireLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){
        travel.setAuthor(userInfo);
        Long travelId = travelService.saveOrUpdate(travel);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.addData(travelId); //返回游记id值
        return ajaxResult;
    }

    //游记评论
    @RequireLogin
    @RequestMapping("/commentAdd")
    public String commentAdd(Long floor, Model model, TravelComment travelComment, @UserParam UserInfo userInfo){
        travelComment.setUserId(userInfo.getId());
        travelComment.setUsername(userInfo.getNickname());
        travelComment.setCity(userInfo.getCity());
        travelComment.setLevel(userInfo.getLevel());
        travelComment.setHeadUrl(userInfo.getHeadImgUrl());
        TravelComment comment = travelCommentService.saveOrUpdate(travelComment);
        model.addAttribute("c", comment);
        model.addAttribute("floor", floor + 1);
        return "travel/commentTpl";
    }

    //顶: 点赞
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long id, @UserParam UserInfo userInfo){ //id为游记id
        if(userInfo == null){
            return new AjaxResult("请先登录", AjaxResult.CODE_TYPE_UNLOGIN);
        }
        boolean ret = travelStatisRedisService.thumbup(id, userInfo.getId());
        return new AjaxResult(ret, "").addData(travelStatisRedisService.getTravelStatisVo(id));
    }

    //收藏
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long tid, @UserParam UserInfo userInfo){ //tid为游记id
        if(userInfo == null){
            return new AjaxResult("请先登录", AjaxResult.CODE_TYPE_UNLOGIN);
        }
        boolean ret = travelStatisRedisService.favor(tid, userInfo.getId());
        return new AjaxResult(ret, "").addData(travelStatisRedisService.getTravelStatisVo(tid));
    }
}
